package com.ywjh.inter.servlet.doc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywjh.inter.conn.MemcacheConn;
import com.ywjh.inter.service.DocService;
import com.ywjh.inter.service.DoctorService;
import com.ywjh.inter.utils.StrUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ListPatient extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6538434777640741849L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=utf-8");

		JSONObject postData = StrUtil.getPostJSON(req);
		System.out.println(postData.toString());
		String act = postData.getString("act");
		JSONObject data = postData.getJSONObject("data");
		int r = 0;
		String e = "";
		JSONObject json = new JSONObject();
		JSONObject d = new JSONObject();
		switch (act) {
		case "list_by_disease":
			int doc_id = data.getInt("doc_id");
			String cache = MemcacheConn.getInstance().get("list_by_disease_doc_" + doc_id);
			if (cache != null) {
				System.out.println("Get Cache key="+"list_by_disease_doc_" + doc_id);
				d = JSONObject.fromObject(cache);
			} else {
				Map<Integer, List<JSONObject>> map = DoctorService.getInstance().listPatientGroupByDisId(doc_id);
				for (Integer key : map.keySet()) {
					String name = DocService.getInstance().getDiseaseName(key);
					if (name == null) {
						name = "未知";
					}
					List<JSONObject> list = map.get(key);
					JSONArray array = new JSONArray();
					for (JSONObject o : list) {
						array.add(o);
					}
					d.put(name, array);
				}
				MemcacheConn.getInstance().put("list_by_disease_doc_" + doc_id, d.toString(), 120);
			}
			r = 1;
			json.put("d", d);
			break;
		}

		json.put("r", r);
		json.put("e", e);
		PrintWriter pw = resp.getWriter();
		pw.write(json.toString());
		pw.flush();
		pw.close();
	}
}
